<?php
require_once '../config/database.php';

// JSON 响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'get_config':
                try {
                    $configKey = $_GET['config_key'] ?? null;
                    if ($configKey) {
                        $stmt = $pdo->prepare("SELECT * FROM museum_config WHERE config_key = ?");
                        $stmt->execute([$configKey]);
                        $config = $stmt->fetch();
                        
                        if ($config) {
                            $value = $config['config_value'];
                            // 根据类型转换值
                            switch ($config['config_type']) {
                                case 'number':
                                    $value = (int)$value;
                                    break;
                                case 'boolean':
                                    $value = (bool)$value;
                                    break;
                                case 'json':
                                    $value = json_decode($value, true);
                                    break;
                            }
                            sendJson([
                                'code' => 200,
                                'message' => '获取成功',
                                'data' => ['value' => $value, 'type' => $config['config_type']]
                            ]);
                        } else {
                            sendJson([
                                'code' => 404,
                                'message' => '配置不存在',
                                'data' => null
                            ]);
                        }
                    } else {
                        // 获取所有配置
                        $stmt = $pdo->query("SELECT * FROM museum_config ORDER BY config_key");
                        $configs = $stmt->fetchAll();
                        $result = [];
                        
                        foreach ($configs as $config) {
                            $value = $config['config_value'];
                            // 根据类型转换值
                            switch ($config['config_type']) {
                                case 'number':
                                    $value = (int)$value;
                                    break;
                                case 'boolean':
                                    $value = (bool)$value;
                                    break;
                                case 'json':
                                    $value = json_decode($value, true);
                                    break;
                            }
                            $result[$config['config_key']] = [
                                'value' => $value,
                                'type' => $config['config_type'],
                                'description' => $config['description']
                            ];
                        }
                        
                        sendJson([
                            'code' => 200,
                            'message' => '获取成功',
                            'data' => $result
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取配置失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'get_time_slots':
                try {
                    $stmt = $pdo->query("SELECT * FROM museum_time_slots ORDER BY sort_order, start_time");
                    $slots = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型
                    foreach ($slots as &$slot) {
                        $slot['id'] = (int)$slot['id'];
                        $slot['max_visitors'] = (int)$slot['max_visitors'];
                        $slot['is_active'] = (int)$slot['is_active'];
                        $slot['sort_order'] = (int)$slot['sort_order'];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $slots
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取时段失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'get_closure_dates':
                try {
                    // 获取所有闭馆规则，用于管理界面显示
                    $stmt = $pdo->query("SELECT * FROM museum_closure_dates ORDER BY created_at DESC");
                    $closures = $stmt->fetchAll();
                    
                    // 确保数值字段为正确的类型
                    foreach ($closures as &$closure) {
                        $closure['id'] = (int)$closure['id'];
                        $closure['is_active'] = (int)$closure['is_active'];
                    }
                    
                    sendJson([
                        'code' => 200,
                        'message' => '获取成功',
                        'data' => $closures
                    ]);
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '获取闭馆日期失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'update_config':
                try {
                    if (!isset($input['config_key']) || !isset($input['config_value'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少必要参数',
                            'data' => null
                        ]);
                    }
                    
                    $configKey = $input['config_key'];
                    $configValue = $input['config_value'];
                    $configType = $input['config_type'] ?? 'string';
                    
                    // 验证配置值
                    switch ($configType) {
                        case 'number':
                            if (!is_numeric($configValue)) {
                                sendJson([
                                    'code' => 400,
                                    'message' => '配置值必须是数字',
                                    'data' => null
                                ]);
                            }
                            break;
                        case 'boolean':
                            $configValue = $configValue ? '1' : '0';
                            break;
                        case 'json':
                            if (is_array($configValue) || is_object($configValue)) {
                                $configValue = json_encode($configValue);
                            }
                            break;
                    }
                    
                    $stmt = $pdo->prepare("
                        UPDATE museum_config 
                        SET config_value = ?, config_type = ?, updated_at = NOW() 
                        WHERE config_key = ?
                    ");
                    $result = $stmt->execute([(string)$configValue, $configType, $configKey]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '更新成功',
                            'data' => ['config_key' => $configKey, 'config_value' => $configValue]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '更新失败，配置项可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新配置失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'add_time_slot':
                try {
                    if (!isset($input['slot_name']) || !isset($input['start_time']) || !isset($input['end_time'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少必要参数',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("
                        INSERT INTO museum_time_slots 
                        (slot_name, start_time, end_time, max_visitors, is_active, sort_order, created_at) 
                        VALUES (?, ?, ?, ?, ?, ?, NOW())
                    ");
                    
                    $result = $stmt->execute([
                        $input['slot_name'],
                        $input['start_time'],
                        $input['end_time'],
                        (int)($input['max_visitors'] ?? 50),
                        (int)($input['is_active'] ?? 1),
                        (int)($input['sort_order'] ?? 0)
                    ]);
                    
                    if ($result) {
                        $id = $pdo->lastInsertId();
                        sendJson([
                            'code' => 200,
                            'message' => '添加成功',
                            'data' => ['id' => $id]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '添加失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '添加时段失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'add_closure_rule':
                try {
                    if (!isset($input['closure_type']) || !isset($input['reason'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少必要参数',
                            'data' => null
                        ]);
                    }
                    
                    $closureType = $input['closure_type'];
                    $reason = $input['reason'];
                    
                    // 根据不同的闭馆类型处理
                    switch ($closureType) {
                        case 'once':
                            if (!isset($input['closure_date'])) {
                                sendJson([
                                    'code' => 400,
                                    'message' => '缺少闭馆日期',
                                    'data' => null
                                ]);
                            }
                            
                            $stmt = $pdo->prepare("
                                INSERT INTO museum_closure_dates 
                                (closure_date, closure_type, reason, is_active, created_at) 
                                VALUES (?, ?, ?, ?, NOW())
                            ");
                            
                            $result = $stmt->execute([
                                $input['closure_date'],
                                'once',
                                $reason,
                                1
                            ]);
                            break;
                            
                        case 'range':
                            if (!isset($input['start_date']) || !isset($input['end_date'])) {
                                sendJson([
                                    'code' => 400,
                                    'message' => '缺少开始或结束日期',
                                    'data' => null
                                ]);
                            }
                            
                            // 为日期范围生成多个单独的记录
                            $startDate = new DateTime($input['start_date']);
                            $endDate = new DateTime($input['end_date']);
                            $interval = new DateInterval('P1D');
                            $period = new DatePeriod($startDate, $interval, $endDate->add($interval));
                            
                            $stmt = $pdo->prepare("
                                INSERT INTO museum_closure_dates 
                                (closure_date, closure_type, reason, is_active, created_at) 
                                VALUES (?, ?, ?, ?, NOW())
                            ");
                            
                            $insertCount = 0;
                            foreach ($period as $date) {
                                $result = $stmt->execute([
                                    $date->format('Y-m-d'),
                                    'range',
                                    $reason,
                                    1
                                ]);
                                if ($result) $insertCount++;
                            }
                            $result = $insertCount > 0;
                            break;
                            
                        case 'weekly':
                        case 'monthly':
                        case 'yearly':
                            // 对于这些复杂类型，暂时用简单的方式处理
                            // 可以在reason字段中保存详细信息
                            $detailInfo = '';
                            if ($closureType === 'weekly' && isset($input['weekdays'])) {
                                $weekNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                                $weekdays = array_map(function($day) use ($weekNames) {
                                    return $weekNames[$day] ?? $day;
                                }, $input['weekdays']);
                                $detailInfo = ' (' . implode('、', $weekdays) . ')';
                            } elseif ($closureType === 'monthly' && isset($input['monthly_day'])) {
                                $detailInfo = ' (每月' . $input['monthly_day'] . '日)';
                            } elseif ($closureType === 'yearly' && isset($input['yearly_month']) && isset($input['yearly_day'])) {
                                $detailInfo = ' (每年' . $input['yearly_month'] . '月' . $input['yearly_day'] . '日)';
                            }
                            
                            $stmt = $pdo->prepare("
                                INSERT INTO museum_closure_dates 
                                (closure_date, closure_type, reason, is_active, created_at) 
                                VALUES (?, ?, ?, ?, NOW())
                            ");
                            
                            $result = $stmt->execute([
                                date('Y-m-d'), // 使用当前日期作为标记
                                $closureType,
                                $reason . $detailInfo,
                                1
                            ]);
                            break;
                            
                        default:
                            sendJson([
                                'code' => 400,
                                'message' => '不支持的闭馆类型',
                                'data' => null
                            ]);
                    }
                    
                    if ($result) {
                        $id = $pdo->lastInsertId();
                        sendJson([
                            'code' => 200,
                            'message' => '闭馆规则添加成功',
                            'data' => ['id' => $id, 'type' => $closureType]
                        ]);
                    } else {
                        sendJson([
                            'code' => 500,
                            'message' => '添加失败',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '添加闭馆规则失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'update_time_slot':
                try {
                    if (!isset($input['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少时段ID',
                            'data' => null
                        ]);
                    }
                    
                    $slotId = (int)$input['id'];
                    $updateData = [];
                    $params = [];
                    
                    // 构建更新字段
                    if (isset($input['slot_name'])) {
                        $updateData[] = 'slot_name = ?';
                        $params[] = $input['slot_name'];
                    }
                    if (isset($input['start_time'])) {
                        $updateData[] = 'start_time = ?';
                        $params[] = $input['start_time'];
                    }
                    if (isset($input['end_time'])) {
                        $updateData[] = 'end_time = ?';
                        $params[] = $input['end_time'];
                    }
                    if (isset($input['max_visitors'])) {
                        $updateData[] = 'max_visitors = ?';
                        $params[] = (int)$input['max_visitors'];
                    }
                    if (isset($input['is_active'])) {
                        $updateData[] = 'is_active = ?';
                        $params[] = (int)$input['is_active'];
                    }
                    
                    if (empty($updateData)) {
                        sendJson([
                            'code' => 400,
                            'message' => '没有要更新的字段',
                            'data' => null
                        ]);
                    }
                    
                    $updateData[] = 'updated_at = NOW()';
                    $params[] = $slotId;
                    
                    $sql = "UPDATE museum_time_slots SET " . implode(', ', $updateData) . " WHERE id = ?";
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '更新成功',
                            'data' => ['id' => $slotId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '更新失败，时段可能不存在或没有变化',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新时段失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'update_closure_rule':
                try {
                    if (!isset($input['id'])) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少闭馆规则ID',
                            'data' => null
                        ]);
                    }
                    
                    $closureId = (int)$input['id'];
                    $updateData = [];
                    $params = [];
                    
                    // 构建更新字段
                    if (isset($input['closure_date'])) {
                        $updateData[] = 'closure_date = ?';
                        $params[] = $input['closure_date'];
                    }
                    if (isset($input['reason'])) {
                        $updateData[] = 'reason = ?';
                        $params[] = $input['reason'];
                    }
                    if (isset($input['is_active'])) {
                        $updateData[] = 'is_active = ?';
                        $params[] = (int)$input['is_active'];
                    }
                    
                    if (empty($updateData)) {
                        sendJson([
                            'code' => 400,
                            'message' => '没有要更新的字段',
                            'data' => null
                        ]);
                    }
                    
                    $updateData[] = 'updated_at = NOW()';
                    $params[] = $closureId;
                    
                    $sql = "UPDATE museum_closure_dates SET " . implode(', ', $updateData) . " WHERE id = ?";
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($params);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '更新成功',
                            'data' => ['id' => $closureId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '更新失败，闭馆规则可能不存在或没有变化',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '更新闭馆规则失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    case 'DELETE':
        switch ($action) {
            case 'delete_time_slot':
                try {
                    $slotId = (int)($_GET['id'] ?? 0);
                    if (!$slotId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少时段ID',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM museum_time_slots WHERE id = ?");
                    $result = $stmt->execute([$slotId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '删除成功',
                            'data' => ['id' => $slotId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '删除失败，时段可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '删除时段失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            case 'delete_closure_date':
                try {
                    $closureId = (int)($_GET['id'] ?? 0);
                    if (!$closureId) {
                        sendJson([
                            'code' => 400,
                            'message' => '缺少闭馆日期ID',
                            'data' => null
                        ]);
                    }
                    
                    $stmt = $pdo->prepare("DELETE FROM museum_closure_dates WHERE id = ?");
                    $result = $stmt->execute([$closureId]);
                    
                    if ($result && $stmt->rowCount() > 0) {
                        sendJson([
                            'code' => 200,
                            'message' => '删除成功',
                            'data' => ['id' => $closureId]
                        ]);
                    } else {
                        sendJson([
                            'code' => 400,
                            'message' => '删除失败，闭馆日期可能不存在',
                            'data' => null
                        ]);
                    }
                } catch (Exception $e) {
                    sendJson([
                        'code' => 500,
                        'message' => '删除闭馆日期失败: ' . $e->getMessage(),
                        'data' => null
                    ]);
                }
                break;
                
            default:
                sendJson([
                    'code' => 400,
                    'message' => '无效的操作',
                    'data' => null
                ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>